package logic

import (
	"boke/moble/cache"
	"boke/moble/mysql"
	"boke/pkg"
	"context"
	"fmt"

	"boke/bokerpc/bokerpc"
	"boke/bokerpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *bokerpc.LoginRequest) (*bokerpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User
	mysql.DB.Debug().Where("mobile = ?", in.Mobile).Find(&user)
	get := cache.Rdb.Get(l.ctx, "captcha"+in.Mobile)
	if get.Val() != in.CaptchaCode {
		return nil, fmt.Errorf("图片验证码错误,请重新输入")
	}
	get2 := cache.Rdb.Get(l.ctx, "sendSms"+in.Mobile)
	if get2.Val() != in.SmsCode {
		return nil, fmt.Errorf("短信验证码错误,请重新输入")
	}

	if user.ID == 0 {
		return nil, fmt.Errorf("该用户未注册,禁止登录")
	}
	if user.Password != pkg.MD5(in.Password) {
		return nil, fmt.Errorf("密码错误,请重新输入")
	}
	mysql.DB.Debug().Find(&user)

	return &bokerpc.LoginResponse{
		Id: int64(user.ID),
	}, nil
}
